<template>
	<view class="container">
		<view class="topContent">
			<view class="topOptions">
				<view class="optionSon">
					<uni-data-select placeholder="切换设备" style="border: none" v-model="curronDevice"
						:localdata="deviceOptionList" :clear="false" @change="changeDeviceOption"></uni-data-select>
				</view>
				<view class="optionSon"></view>
				<view class="optionSon"></view>
				<view class="optionSon addopson">
					<view class="gear-container" @click="showMenu">
						<uni-icons type="gear" size="26" color="#fff"></uni-icons>
						<view class="dropdown-menu" v-if="showDropdown">
							<!-- <view class="dropdown-item" @click="toPasswordChange">
								<uni-icons type="locked" size="20"></uni-icons>
								<text style="color: #000">密码修改</text>
							</view> -->
							<view class="dropdown-item" @click="deviceUnbind">
								<uni-icons type="locked" size="20"></uni-icons>
								<text style="color: #000">设备解绑</text>
							</view>
						</view>
					</view>
					<uni-icons type="plus" size="26" color="#fff" @click="addDianXiangFn"></uni-icons>
				</view>
			</view>
			<swiper class="swiper topBox" :current="keyIndex" :next-margin="40" :previous-margin="10"
				@change="changeSwiper">
				<template v-if="deviceList.length">
					<swiper-item class="topLeft deviceItem" v-for="item in deviceList">
						<view class="header">
							<view>
								<view class="headerImg" :style="{
                    backgroundImage: `url(${item.device_img})`,
                    width: '150rpx',
                  }">
								</view>
							</view>
							<view>
								<view style="display: flex; align-items: center">
									{{ item.device_name }}
									<!-- <text v-if="item.online == 1" class="outLine">在线</text>
                  <text v-else class="online">离线</text> -->
								</view>
								<span>编号:{{ item.mac }}</span>
							</view>
							<view style="font-size: 24rpx; color: #ccc"></view>
						</view>
						<view class="main">
							<view class="mainBox" @click="toYongDian">
								<view class="enger">
									<view>本日用电量：</view>
									<view><text class="numEn">{{ item.day_power }}</text>KWh</view>
								</view>
								<view class="enger">
									<view>本月用电量：</view>
									<view><text class="numEn">{{ item.month_power }}</text>KWh</view>
								</view>
							</view>
							<view class="warningBox">
								<view>未处理告警</view>
								<view class="warningBox2">
									<view>
										<view class="boxBj warringIcon"></view>
										<view>{{ item.warning_num }}</view>
									</view>
									<view>
										<view class="boxBj errorIcon"></view>
										<view>{{ item.alarm_num }}</view>
									</view>
								</view>
							</view>
						</view>
					</swiper-item>
				</template>

				<swiper-item class="topRight deviceItem">
					<span></span>
					<view @click="addDianXiangFn">
						<view style="text-align: center">
							<uni-icons type="plusempty" size="30"></uni-icons>
						</view>
						<view style="font-size: 26rpx">添加电箱</view>
					</view>
					<span></span>
				</swiper-item>
			</swiper>
		</view>
		<view class="methods">
			<view class="methodsSon" @click="toSonPage('/wuLian/pages/shiJianJiLu?mac=' + curronDevice.mac)">
				<view class="msBox shijian"></view>
				<view>事件记录</view>
			</view>
			<view class="methodsSon" @click="
          toSonPage('/wuLian/pages/louDianZiJian?mac=' + curronDevice.mac)
        ">
				<view class="msBox loudian"></view>
				<view>漏电自检</view>
			</view>
			<view class="methodsSon" @click="
          toSonPage('/wuLian/pages/DingShi/index?mac=' + curronDevice.mac)
        ">
				<view class="msBox dingshi"></view>
				<view>定时控制</view>
			</view>
			<view class="methodsSon" @click="piLiang()">
				<view class="msBox hezha"></view>
				<view>批量分合闸</view>
			</view>
		</view>
		<view style="margin: 0 20rpx; padding-bottom: 50rpx">
			<uni-section title="控制管理" type="line">
				<view :is-shadow="false" v-for="sonItem in lines" class="boxKZ" @click="waiceng(sonItem)">
					<view style="
              font-weight: 600;
              color: #000;
              padding-bottom: 20rpx;
              display: flex;
            ">
						<view>{{ sonItem.title }}</view>
						<view>
							<text class="btns1 fz" v-if="sonItem.OpenClose == 'false'">已分闸</text>
							<text class="btns1 hz" v-else>已合闸</text>
						</view>
					</view>
					<view class="gridBox">
						<uni-grid :column="7" :show-border="false">
							<uni-grid-item :index="0">
								<view class="gridVal">{{ sonItem.A_V }}V</view>
								<view>电压</view>
							</uni-grid-item>
							<uni-grid-item :index="1">
								<view class="gridVal">{{ sonItem.A_A }}A</view>
								<view>电流</view>
							</uni-grid-item>
							<uni-grid-item :index="2">
								<view class="gridVal">{{ sonItem.A_WP }}W</view>
								<view>功率</view>
							</uni-grid-item>
							<uni-grid-item :index="3">
								<view class="gridVal">{{ sonItem.A_T }}℃</view>
								<view>温度</view>
							</uni-grid-item>
							<uni-grid-item :index="4">
								<view class="gridVal">{{ sonItem.A_PF }}</view>
								<view>功率因数</view>
							</uni-grid-item>
							<uni-grid-item :index="5">
								<view class="gridVal">{{ sonItem.A_LD }}mA</view>
								<view>漏电流</view>
							</uni-grid-item>
							<uni-grid-item :index="6">
								<text @click.stop="hezhaFn(sonItem)" class="btns fz"
									v-if="sonItem.OpenClose == 'true'">分闸</text>
								<text @click.stop="hezhaFn(sonItem)" class="btns hz" v-else>合闸</text>
							</uni-grid-item>
						</uni-grid>
					</view>
				</view>
			</uni-section>
		</view>
	</view>
	<uni-popup ref="popupSelect" :mask-click="false">
		<view style="
        text-align: center;
        background-color: #fff;
        border-top-right-radius: 10rpx;
        padding: 20rpx;
        border-top-left-radius: 10rpx;
        display: flex;
        justify-content: space-between;
      ">
			<view></view>
			<view>批量分合闸</view>
			<view><uni-icons type="clear" size="24" @click="popupSelect.close()"></uni-icons></view>
		</view>
		<view style="background-color: #fff; display: flex; justify-content: center;align-items: center;">
			<view class="btnsCheck" @click="btnsCheckFn('all')">全选</view>
			<view class="btnsCheck" @click="btnsCheckFn('fan')">反选</view>
		</view>
		<scroll-view style="
        height: 400rpx;
        width: 600rpx;
        background-color: #fff;
        font-size: 24rpx;
      " scroll-y="true">
			<view class="uni-list">
				<checkbox-group @change="checkboxChange">
					<label class="uni-list-cell uni-list-cell-pd" style="display: flex; padding: 20rpx"
						v-for="sonItem in lines" :key="sonItem">
						<view>
							<checkbox :value="sonItem.addr" :checked="sonItem.checked" />
						</view>
						<view>{{ sonItem.title }}</view>
					</label>
				</checkbox-group>
			</view>
		</scroll-view>
		<view style="
        display: flex;
        justify-content: center;
        gap: 20rpx;
        background-color: #fff;
        padding: 20rpx 0rpx;
      ">
			<text class="btns btn" @click="plFn">分闸</text><text class="btns btn" @click="plFzFN">合闸</text>
		</view>
	</uni-popup>
	<!-- 输入框示例 -->
	<uni-popup ref="heZhaDialog" type="dialog">
		<!-- 		<uni-popup-dialog ref="inputClose" :focus="false" mode="input" inputType="password" title="请输入当前设备密码"
			placeholder="请输入密码" @confirm="hezhaFnCofrim"></uni-popup-dialog> -->
		<uni-popup-dialog type="warn" cancelText="取消" confirmText="确定" title="提示" content="是否确认此操作？"
			@confirm="hezhaFnCofrim" @close="heZhaDialog.close()"></uni-popup-dialog>
	</uni-popup>
	<!-- 密码修改菜单 -->
	<uni-popup ref="menuPopup" type="bottom">
		<view class="menu-content">
			<view class="menu-item" @click="toPasswordChange">
				<uni-icons type="locked" size="20"></uni-icons>
				<text>密码修改</text>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import {
		onShow,
		onHide,
		onLoad,
		onBackPress
	} from "@dcloudio/uni-app";
	import {
		getDeviceDetail,
		changeLineStatus,
		checkPassword,
		delBindDevice,
		setUploadFrequency
	} from "@/api/wuLian.js";
	import {useWuLianStore} from "@/stores/wuLian.js"
	const wuLianStore = useWuLianStore()
	import {
		getUser
	} from "@/utils/token.js";
	import {
		ref,
		onUnmounted
	} from "vue";
	let typeDomStr = ""
	let tempLineVal = ""
	function toYongDian(){
		uni.navigateTo({
			url:"/wuLian/pages/yongDianTongJi?mac="+curronDevice.value.mac
		})
	}
	function btnsCheckFn(type) {
		console.log(lines.value, type, 252)
		console.log(checkedArr.value, 253)
		typeDomStr = type
		if (type === 'all') {
			checkedArr.value = []
			for (let i = 0; i < lines.value.length; i++) {
				lines.value[i].checked = true
				checkedArr.value.push(lines.value[i].addr)
			}
		}
		if (type === 'fan') {
			let tmpArr = []
			for (let i = 0; i < lines.value.length; i++) {
				if (!checkedArr.value.includes(lines.value[i].addr)) {
					lines.value[i].checked = true
					tmpArr.push(lines.value[i].addr)
				} else {
					lines.value[i].checked = false
				}
			}
			checkedArr.value = tmpArr
		}
		// if (tempLine) {
		// 	lines.value = tempLine
		// }
		// tempLine = JSON.parse(JSON.stringify(lines.value))

	}
	onLoad((evt) => {
		console.log(evt, 242)
		options.value = evt ? evt : {
			id: 0
		}

	})
	const qieHuanIndex = ref([])
	const keyIndex = ref(0)
	const options = ref()
	const heZhaDialog = ref();
	const popupSelect = ref();
	const menuPopup = ref();

	function piLiang() {
		plFlag.value = true;
		for (let i = 0; i < lines.value.length; i++) {
			lines.value[i].checked = false
		}
		heZhaDialog.value.open();
	}

	const deviceList = ref([]);
	let user = getUser();
	const lines = ref([]);
	const curronDevice = ref({});

	function toSonPage(item) {
		wuLianStore.setnowId(curronDevice.value.id)
		uni.navigateTo({
			url: item,
		});
	}

	function waiceng(item) {
		console.log(curronDevice.value.id,317)
		wuLianStore.setnowId(curronDevice.value.id)
		uni.navigateTo({
			url: `/wuLian/pages/device/detail?mac=${curronDevice.value.mac}&addr=${item.addr}`,
		});
	}
	
	function deviceUnbind() {
		delBindDevice({
			mac: curronDevice.value.mac,
			customer_id: user.id
		}).then(
			(e) => {
				if (e.code == 0) {
					uni.showToast({
						title: "解绑成功",
						icon: "success",
					});
					uni.redirectTo({
						url: "/wuLian/pages/index",
					});
				}
			}
		);
	}
	const deviceOptionList = ref([]);

	function changeDeviceOption(item) {
		console.log(item, 202);
	}
	let timerInv = null;
	onShow(() => {
		if(wuLianStore.nowId){
			options.value.id = wuLianStore.nowId
			wuLianStore.setnowId(0)
		}
		console.log(351)
		user = getUser();
		showDropdown.value = false;
		if (!user.id) {
			uni.navigateTo({
				url: "/wuLian/pages/login",
			});
		} else {
			getDeviceDetail(user.id).then((e) => {
				deviceList.value = e.data;
				let index = 0
				deviceOptionList.value = e.data.map((item) => {
					qieHuanIndex.value[`a_${item.id}`] = index
					index++
					return {
						text: item.device_name,
						value: item,
					};

				});

				keyIndex.value = qieHuanIndex.value['a_' + options.value.id]
				if (!keyIndex.value) {
					keyIndex.value = 0
				}
				// keyIndex.value = qieHuanIndex.value
				lines.value = e.data[keyIndex.value].lines;
				curronDevice.value = e.data[keyIndex.value];
				get180()
			});
			timerInv = setInterval(() => {
				getDeviceDetail(user.id).then((e) => {
					// 检查数据是否有变化
					const hasDataChanged = JSON.stringify(e.data) !== JSON.stringify(deviceList
						.value);

					if (hasDataChanged) {
						deviceList.value = e.data;
						let index = 0
						deviceOptionList.value = e.data.map((item) => {
							qieHuanIndex.value[`a_${item.id}`] = index
							index++
							return {
								text: item.device_name,
								value: item,
							};
						});

						// 只有当数据变化时才更新当前设备信息
						if (e.data[keyIndex.value]) {
							// typeDomStr
							console.log(popupSelectFlag.value, 383)
							if (!popupSelectFlag.value) {
								lines.value = e.data[keyIndex.value].lines;
							}
							curronDevice.value = e.data[keyIndex.value];
						}
					}
				});
			}, 5000);
		}
	});
	let inv180 = null

	function get180() {
		setUploadFrequency({
			mac: curronDevice.value.mac
		})
		inv180 = setInterval(() => {
			console.log("354setUploadFrequency")
			setUploadFrequency({
				mac: curronDevice.value.mac
			})
		}, 540000)

	}
	onHide(() => {
		clearInterval(timerInv);
		clearInterval(inv180)
		timerInv = null;
		inv180 = null
	});
	onUnmounted(() => {
		clearInterval(timerInv);
		clearInterval(inv180)
		timerInv = null;
		inv180 = null
	});
	const tempLine = ref({});

	function hezhaFn(item) {
		tempLine.value = item;
		heZhaDialog.value.open();
	}
	const plFlag = ref(false);
	const popupSelectFlag = ref(false)

	function hezhaFnCofrim(e) {
		// checkPassword({
		// 	mac: curronDevice.value.mac,
		// 	password: e
		// }).then((e) => {
		// 	if (e.code == 0) {
		if (plFlag.value) {
			// 循环线 去掉选中状态
			typeDomStr = ""
			popupSelect.value.open();
			popupSelectFlag.value = true
			plFlag.value = false;
			console.log(407)
		} else {
			console.log(409)
			hezhaFnRes(tempLine.value);
		}
		// } else {
		// 	uni.showToast({
		// 		icon: "none",
		// 		title: e.msg,
		// 	});
		// }
		// });
		//   if (e == curronDevice.value.device_pwd) {
		//     uni.showToast({
		//       icon: "none",
		//       title: "密码正确",
		//     });
		//   if (plFlag.value) {
		//     popupSelect.value.open();
		//     plFlag.value = false;
		//   } else {
		//     hezhaFnRes(tempLine.value);
		//   }
		//   } else {
		//     uni.showToast({
		//       icon: "none",
		//       title: "密码错误，请确认再试！",
		//     });
		//   }
	}

	function hezhaFnRes(item) {
		let tempval1, tempval2;
		tempval2 = item.addr;
		if (item.OpenClose == 'true') {
			tempval1 = "close";
			// item.oc = 0
		} else {
			tempval1 = "open";
			// item.oc = 1
		}
		changeLineStatus({
			mac: curronDevice.value.mac,
			value1: tempval1,
			value2: tempval2,
		}).then((e) => {
			if (e.code == 0) {
				uni.showToast({
					title: "设置成功",
				});
				// if (item.OpenClose == "true") {
				//   // tempval1 = 'close'
				//   item.OpenClose = "false";
				// } else {
				//   // tempval1 = 'open'
				//   item.OpenClose = "true";
				// }
			} else {
				uni.showToast({
					icon: "none",
					title: e.msg,
				});
			}
		});
	}

	function addDianXiangFn() {
		uni.navigateTo({
			url: "/dianXiang/pages/index",
		});
	}
	// 跳转到事件记录页面
	function goRecord() {
		uni.navigateTo({
			url: "/wuLian/pages/shiJianJiLu",
		});
	}
	// 跳转到漏电自检页面
	function goCheck() {
		uni.navigateTo({
			url: "/wuLian/pages/louDianZiJian",
		});
	}

	function getList() {
		getDeviceDetail(user.id).then((e) => {
			// 检查数据是否有变化
			const hasDataChanged = JSON.stringify(e.data) !== JSON.stringify(deviceList.value);

			if (hasDataChanged) {
				deviceList.value = e.data;
				lines.value = e.data[0].lines;
				curronDevice.value = e.data[0];
			}
		});
	}
	// 跳转到定时控制
	function goControl() {
		uni.navigateTo({
			url: "/wuLian/pages/DingShi/index",
		});
	}

	function plFn() {
		console.log(checkedArr.value.join(","), 244);
		changeLineStatus({
			mac: curronDevice.value.mac,
			value1: "close",
			value2: checkedArr.value.join(","),
		}).then((e) => {
			uni.showToast({
				title: "设置成功",
			});
			getList();
			popupSelectFlag.value = false
			popupSelect.value.close();
		});
	}

	function plFzFN() {
		console.log(checkedArr.value.join(","), 244);
		changeLineStatus({
			mac: curronDevice.value.mac,
			value1: "open",
			value2: checkedArr.value.join(","),
		}).then((e) => {
			if (e.code == 0) {
				uni.showToast({
					title: "设置成功",
				});
				getList();
			} else {
				uni.showToast({
					icon: "none",
					title: e.msg,
				});
			}
			popupSelectFlag.value = false
			popupSelect.value.close();
		});
	}
	const checkedArr = ref([]);

	function checkboxChange(item) {
		checkedArr.value = item.detail.value;
		console.log(item, 588)
	}

	function changeSwiper(evt) {
		// console.log(evt.detail.current, 281);
		keyIndex.value = evt.detail.current
		if (deviceList.value.length == evt.detail.current) {
			lines.value = [];
			curronDevice.value = [];
		} else {
			lines.value = deviceList.value[evt.detail.current].lines;
			curronDevice.value = deviceList.value[evt.detail.current];
		}
	}

	const showDropdown = ref(false);

	function showMenu() {
		showDropdown.value = !showDropdown.value;
	}

	function toPasswordChange() {
		wuLianStore.setnowId(curronDevice.value.id)
		showDropdown.value = false;
		uni.navigateTo({
			url: `/wuLian/pages/device/editpassword?mac=${curronDevice.value.mac}`,
		});
	}
</script>

<style scoped>
	.topContent {
		padding-top: 20rpx;
		height: 500rpx;
		background: linear-gradient(to bottom, #e60012, #e6001200);
	}

	.topOptions {
		display: flex;
	}

	.optionSon {
		flex: 1;
	}

	::v-deep .uni-select {
		border: none !important;
	}

	::v-deep .uni-select__input-placeholder {
		color: #fff;
	}

	::v-deep .uni-select__input-text {
		color: #fff;
	}

	::v-deep .uniui-bottom {
		color: #fff !important;
	}

	.addopson {
		font-size: 26rpx;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin-right: 20rpx;
	}

	.online {
		color: #fff;
		border-radius: 20rpx;
		font-size: 20rpx;
		padding: 0rpx 20rpx;
		background-color: #f5d976;
		/* line-height: 20rpx; */
	}

	.outLine {
		color: #fff;
		border-radius: 20rpx;
		font-size: 20rpx;
		padding: 0rpx 20rpx;
		background-color: green;
		/* line-height: 20rpx; */
	}

	.deviceItem {
		margin-right: 20rpx;
		background-color: #ffffff;
		border: 4px solid;
		border-image: linear-gradient(to bottom, #e60012, #e6001210) 1;
		border-radius: 20rpx;
		padding: 0 10rpx;
	}

	.uni-list-cell {
		justify-content: flex-start;
	}

	.headerImg {
		width: 150rpx;
		height: 150rpx;
		background-position: center;
		background-repeat: no-repeat;
		background-size: contain;
	}

	.header {
		margin-top: 20rpx;
	}

	.enger {
		background: #ececec;
		display: flex;
		font-size: 26rpx;
		line-height: 50rpx;
		padding: 1rpx 20rpx;
		border-radius: 10rpx;
	}

	.numEn {
		font-size: 36rpx;
		color: red;
		font-weight: 600;
	}

	.mainBox {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		justify-content: center;
	}

	.warningBox {
		background-color: #ececec;
		width: 160rpx;
		text-align: center;
		font-size: 24rpx;
		border-radius: 10rpx;
	}

	.main {
		display: flex;
		gap: 20rpx;
		padding: 20rpx;
	}

	.warningBox2 {
		display: flex;
		gap: 20rpx;
		justify-content: center;
		font-size: 32rpx;
		font-weight: 600;
	}

	.boxBj {
		width: 60rpx;
		height: 60rpx;
		background-repeat: no-repeat;
		background-size: 100% 100%;
		background-position: center;
	}

	.warringIcon {
		background-image: url("/static/warring.png");
	}

	.errorIcon {
		background-image: url("/static/error.png");
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.topBox {
		margin-top: 20rpx;
		height: 350rpx;
		padding-bottom: 30px;
		background: linear-gradient(to bottom, #e60012, #e6001200);
		/* 	background-color: #fff; */
	}

	.container {
		background-color: #f7f7f7;
	}

	.methods {
		display: flex;
		gap: 20rpx;
		justify-content: center;
		margin: 20rpx 20rpx;
		background-color: #fff;
		height: 200rpx;
		padding: 20rpx 20rpx;
	}

	.methodsSon {
		display: flex;
		flex-direction: column;
		flex: 1;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
	}

	.msBox {
		height: 120rpx;
		width: 100%;
		background-repeat: no-repeat;
		background-position: center;
		background-size: 60%;
	}

	.shijian {
		background-image: url("/static/shijian.png");
	}

	.dingshi {
		background-image: url("/static/dingshi.png");
	}

	.loudian {
		background-image: url("/static/loudian.png");
	}

	.hezha {
		background-image: url("/static/dianzha.png");
	}

	.gridBox {
		font-size: 24rpx;
		text-align: center;
	}

	.gridVal {
		font-weight: 600;
		margin-bottom: 20rpx;
	}

	.btns {
		padding: 10rpx 10rpx;
		color: #fff;
	}

	.btnsCheck,
	.btn {
		background-color: cornflowerblue;
		font-size: 24rpx;
		padding: 10rpx 30rpx;
	}

	.btnsCheck,
	.btns1 {
		padding: 5rpx 10rpx;
		color: #fff;
		font-size: 24rpx;
		margin-left: 20rpx;
	}

	.fz {
		background-color: red;
	}

	.hz {
		background-color: green;
	}

	.boxKZ {
		border: 1px solid #ccc;
		margin-top: 20rpx;
		padding: 10rpx;
	}

	.topRight {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 20rpx;
	}

	.menu-content {
		background-color: #fff;
		padding: 20rpx;
	}

	.menu-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		gap: 20rpx;
		font-size: 28rpx;
	}

	.menu-item:active {
		background-color: #f5f5f5;
	}

	.gear-container {
		position: relative;
		display: inline-block;
	}

	.dropdown-menu {
		position: absolute;
		top: 100%;
		right: 0;
		background-color: #fff;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
		min-width: 250rpx;
	}

	.dropdown-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		gap: 20rpx;
		font-size: 28rpx;
	}

	.dropdown-item:active {
		background-color: #f5f5f5;
	}
</style>